package com.jeeplus.modules.common.excel.common.validator.impl.base;

import com.jeeplus.modules.common.excel.common.anno.Unique;
import com.jeeplus.modules.common.excel.common.anno.custorm.UniqueData;
import com.jeeplus.modules.common.excel.common.validator.abs.AbstractValidator;
import com.jeeplus.modules.common.excel.common.validator.impl.unique.UniqueDataValidator;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wang.yishu
 * @version 1.0
 * @className UniqueValidator
 * @description 根据单个属性判断唯一性组件
 * @date 2022/7/13 16:24
 */
public class UniqueValidator extends AbstractValidator {

    private Unique unique;

    @Override
    public boolean canValidate(Field field) {
        this.unique = field.getDeclaredAnnotation(Unique.class);
        return this.unique != null;
    }

    @Override
    public String toValidate(Object entity, Field field) {
        Map<String, List<Object>> necessaryValidateData = this.chain.getNecessaryValidateData();
        List<Object> importData = necessaryValidateData.get(UniqueDataValidator.key);
        if (importData.size() > 0) {
            try {
                field.setAccessible(true);
                Object value = field.get(entity);
                if (value == null) return null;
                String valueStr = value.toString();
                List<Object> collect = importData.stream().filter(obj -> {
                    try {
                        Field targetField = obj.getClass().getDeclaredField(field.getName());
                        targetField.setAccessible(true);
                        Object targetValue = targetField.get(obj);
                        String targetValueStr = targetValue == null ? "" : targetValue.toString();
                        return targetValueStr.equals(valueStr);
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        return false;
                    }
                }).collect(Collectors.toList());
                if (collect.size() > 1) {
                    return this.unique.msg();
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
